<template>
    <el-drawer v-model="drawerBool" size="400" @closed="clearDrawer">
        <template #header>
            <h4 v-if="addBool">添加患者信息</h4>
            <h4 v-else>修改患者信息</h4>
        </template>
        <template #default>
            <el-scrollbar>
                <div class="userFormClass">
                    <el-form ref="formRef" :model="formVal" :rules="rules" hide-required-asterisk label-position="left"
                             label-width="85px">
                        <el-form-item class="img" label="头像">
                            <el-upload
                                    :action="BaseConfig.imageUploadURL"
                                    :before-upload="beforeAvatarUpload"
                                    :headers="tokenHeader"
                                    :on-success="handleAvatarSuccess"
                                    :show-file-list="false"
                                    class="avatar-uploader"
                            >
                                <img v-if="formVal.picture" :src="`/api/images/${formVal.picture}`" alt=""
                                     class="avatar img"/>
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus/>
                                </el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="名称" prop="uname">
                            <el-input v-model="formVal.uname"/>
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <el-input v-model.number="formVal.age"/>
                        </el-form-item>
                        <el-form-item label="身份证号码" prop="idCard">
                            <el-input v-model="formVal.idCard"/>
                        </el-form-item>
                        <el-form-item label="电话" prop="telephone">
                            <el-input v-model.number="formVal.telephone"/>
                        </el-form-item>
                        <el-form-item label="手机类型" prop="phone">
                            <el-radio-group v-model="formVal.phone">
                                <el-radio :label="true" border>智能机</el-radio>
                                <el-radio :label="false" border>老年机</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="房间编号" prop="roomId">
                            <el-input-number v-model.number="formVal.roomId" :disabled="info.bool" :min="1"
                                             controls-position="right"
                                             style="width: 100%"/>
                        </el-form-item>
                        <el-form-item label="地址详情" prop="address">
                            <el-input v-model.number="formVal.address" maxlength="100" show-word-limit type="textarea"/>
                        </el-form-item>
                        <el-form-item label="备注" prop="userRemark">
                            <el-input v-model.number="formVal.userRemark" :placeholder="BaseConfig.defaultText" autosize
                                      maxlength="150"
                                      show-word-limit
                                      type="textarea"/>
                        </el-form-item>
                    </el-form>
                </div>
            </el-scrollbar>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClick">取消</el-button>
                <el-button type="primary" @click="confirmClick(formRef)">提交</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang='ts' setup>
import { ref } from 'vue'
import { User } from '@/ts/type/User'
import { Message, Notification } from '@/plugins/element'
import { useStaff, useToken } from '@/store'
import { FormInstance, UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { BaseConfig } from '@/config/config'
import { EventBus } from '@/utils/mitt'
import UserService from '@/api/userApi'
import { rules } from '@/config/formConfig'
import { storeToRefs } from 'pinia'

const Staff = useStaff()
const { info } = storeToRefs(Staff)
const Token = useToken()
const tokenHeader = { Authorization: Token.token }
const drawerBool = ref(false)
const formVal = ref<User>({ roomId: 1 })
const formRef = ref<FormInstance>()
const addBool = ref<boolean>(true)

const handleAvatarSuccess: UploadProps['onSuccess'] = response => {
  const { virtualPath } = response
  formVal.value.picture = virtualPath
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.size / 1024 / 1024 > 1) {
    Notification.error('上传文件的大小必须小于1MB')
    return false
  }
  return true
}
const cancelClick = () => {
  drawerBool.value = false
}

const clearDrawer = () => {
  formVal.value = {}
}

const dealSubmit = () => {
  if (addBool.value) {
    UserService.postUser(formVal.value)
      .then(res => {
        const { data } = res
        Notification.success(data)
        EventBus.emit('searchUser', { bool: false })
        drawerBool.value = false
      })
      .catch(error => {
        drawerBool.value = true
      })
  } else {
    UserService.putUser(formVal.value).then(res => {
      const { data } = res
      Notification.success(data)
      EventBus.emit('searchUser', { bool: false })
      drawerBool.value = false
    })
      .catch(error => {
        drawerBool.value = true
      })
  }
}

const confirmClick = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      dealSubmit()
    } else {
      Message.error('请检查输入内容')
    }
  })
}
EventBus.on('addUser', res => {
  const { bool } = res
  addBool.value = bool
  drawerBool.value = bool
})
EventBus.on('updateUser', async res => {
  const { userId } = res
  await UserService.getUserById(userId).then(res => {
    formVal.value = res.data
  })
  addBool.value = false
  drawerBool.value = true
})
</script>

<style lang='scss' scoped>
.userFormClass {
  padding: 10px 20px;

  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  :deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }
}
</style>